<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索关键字"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceType">
        <el-select
          v-model="form.serviceType"
          placeholder="请选择"
          filterable
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in taskConfigStore.serviceTypes"
            :key="item.standardCode"
            :label="item.displayName"
            :value="item.standardCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-select
          v-model="form.country"
          placeholder="请选择"
          filterable
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in countryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in TASK_STATUS_LIST"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="time">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button type="success" :loading="syncLoading" @click="syncTask">
          刷新页面
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      show-overflow-tooltip
      stripe
      :data="tableData"
      border
    >
      <el-table-column
        prop="taskNo"
        align="center"
        label="任务编号"
        width="220"
      >
        <template #default="scope">
          <el-button
            text
            bg
            round
            class="!text-[#409EFF]"
            @click="copyTask(scope.row.taskNo)"
          >
            {{ scope.row.taskNo }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        label="任务名称"
        align="center"
        min-width="260"
      />
      <el-table-column prop="progress" label="进度" align="center" width="200">
        <template #default="scope">
          <el-progress
            text-inside
            :stroke-width="18"
            :percentage="scope.row.progress"
            :color="customColorMethod"
            status="success"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="totalCount"
        label="数据总量"
        align="center"
        width="120"
      />
      <el-table-column
        prop="effectiveCount"
        label="有效数量"
        align="center"
        width="120"
      />
      <el-table-column
        prop="successCount"
        label="成功数量"
        align="center"
        width="120"
      />
      <el-table-column
        prop="taskStatus"
        label="状态"
        align="center"
        width="120"
      >
        <template #default="scope">
          <el-button
            :type="scope.row.taskStatus === '已完成' ? 'success' : 'danger'"
            round
            size="small"
            :icon="scope.row.taskStatus === '已完成' ? CircleCheck : Warning"
          >
            {{ scope.row.taskStatus }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="pointsCost"
        label="价格"
        align="center"
        width="100"
      />
      <el-table-column prop="country" label="国家" align="center" width="100" />
      <el-table-column
        prop="fileName"
        label="上传文件名"
        align="center"
        min-width="180"
      />
      <el-table-column
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
        align="center"
        min-width="120"
      />
      <el-table-column label="操作" fixed="right" align="center" width="340">
        <template #default="scope">
          <el-button
            v-if="activeDown(scope.row.serviceType)"
            link
            type="success"
            :disabled="scope.row.taskStatus !== '已完成'"
            @click="handleDownloadDialog(scope.row.id)"
          >
            下载结果文件
          </el-button>

          <el-button
            v-else
            link
            type="success"
            :disabled="scope.row.taskStatus !== '已完成'"
            :loading="scope.row.outputLoading"
            @click="handleDownload(scope.row.serviceType, scope.row.id)"
          >
            下载结果文件
          </el-button>
          <el-button
            v-if="forcePhoneList.includes(scope.row.serviceType)"
            link
            type="success"
            :disabled="scope.row.taskStatus !== '已完成'"
            :loading="scope.row.outputLoading"
            @click="downNoRes(scope.row.id)"
          >
            下载无效结果
          </el-button>
          <el-button
            v-if="forceEmailList.includes(scope.row.serviceType)"
            link
            type="success"
            :disabled="scope.row.taskStatus !== '已完成'"
            :loading="scope.row.outputLoading"
            @click="downNoEmailRes(scope.row.id)"
          >
            下载无效结果
          </el-button>
          <el-button
            link
            type="success"
            :loading="scope.row.inputLoading"
            @click="
              handleDownload(scope.row.serviceType, scope.row.id, 'INPUT')
            "
          >
            下载上传文件
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <DownloadFileDialog ref="downloadFileDialogRef" />
  </div>
</template>

<script lang="ts" setup>
import { handleAutoUTC8 } from "@/utils/tools";
import { reactive, ref, onMounted, watch, computed } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  getUserTasks,
  downloadTaskResultFile,
  syncTaskStatus,
  downloadPhonesOnly,
  downloadEmailsOnly
} from "@/api/taskApi";
import { useTaskConfigHook } from "@/store/modules/taskConfig";
import { message } from "@/utils/message";
import DownloadFileDialog from "../userTaskTable/components/DownloadFileDialog.vue";
import { CircleCheck, Warning } from "@element-plus/icons-vue";
import { TASK_STATUS_LIST } from "@/utils/constant";
import { useClipboard } from "@vueuse/core";

const { copy } = useClipboard();
const copyTask = (taskNo: string) => {
  copy(taskNo);
  message("任务编号复制成功", {
    type: "success"
  });
};
const taskConfigStore = useTaskConfigHook();
const formRef = ref();
const loading = ref(false);
const downloadFileDialogRef = ref();
const countryList = computed(() => taskConfigStore.allCountryList);
const form = reactive({
  serviceType: "",
  time: "",
  keyword: "",
  status: "",
  country: "",
  startDate: "",
  endDate: ""
});
const customColorMethod = (percentage: number) => {
  if (percentage < 30) {
    return "#e6a23c";
  }
  if (percentage < 80) {
    return "#409eff";
  }
  return "#67c23a";
};
const syncLoading = ref(false);
const syncTask = async () => {
  try {
    syncLoading.value = true;
    await onSearch();
    message("同步成功", {
      type: "success"
    });
  } catch (error) {
    console.log(error);
  } finally {
    syncLoading.value = false;
  }
};
const pagination = reactive({
  total: 0,
  pageSize: 20,
  currentPage: 1
});
const activeDown = (name: string) => {
  const tags = ["live", "profile"];
  return tags.some(tag => name.includes(tag));
};
// 强制下载手机号
const forcePhoneList = ["ws_activate", "speedy_activate", "fb_activate"];
const forceEmailList = [
  "amazon_email_activate",
  "fb_email_activate",
  "ios_activate"
];
const downNoRes = async (id: number) => {
  const index = tableData.value.findIndex(item => item.id === id);
  try {
    tableData.value[index].outputLoading = true;
    await downloadPhonesOnly(id, true);
  } catch (error) {
    console.log(error);
  } finally {
    tableData.value[index].outputLoading = false;
  }
};
const downNoEmailRes = async (id: number) => {
  const index = tableData.value.findIndex(item => item.id === id);
  try {
    tableData.value[index].outputLoading = true;
    await downloadEmailsOnly(id, true);
  } catch (error) {
    console.log(error);
  } finally {
    tableData.value[index].outputLoading = false;
  }
};
const filterMap = {
  rcs_activate: ["国家", "类型", "手机号", "(效力度，out:无效；in:有效)"],
  tg_activate: ["手机号", "用户名"],
  ins_activate: ["国家", "类型", "手机号"]
};
const handleDownload = async (
  serviceType: string,
  id: number,
  fileType = "OUTPUT"
) => {
  const index = tableData.value.findIndex(item => item.id === id);
  try {
    if (fileType === "OUTPUT") {
      tableData.value[index].outputLoading = true;
    } else {
      tableData.value[index].inputLoading = true;
    }
    if (forcePhoneList.includes(serviceType) && fileType === "OUTPUT") {
      await downloadPhonesOnly(id, false);
    } else if (forceEmailList.includes(serviceType) && fileType === "OUTPUT") {
      await downloadEmailsOnly(id, false);
    } else {
      await downloadTaskResultFile(id, { fileType });
    }
  } catch (error) {
    console.log(error);
  } finally {
    if (fileType === "OUTPUT") {
      tableData.value[index].outputLoading = false;
    } else {
      tableData.value[index].inputLoading = false;
    }
  }
};
const handleDownloadDialog = (id: number) => {
  downloadFileDialogRef.value?.open(id);
};

const tableData = ref([]);

watch(
  () => form.time,
  (newVal, oldVal) => {
    if (newVal) {
      form.startDate = newVal[0];
      form.endDate = newVal[1];
    } else {
      form.startDate = "";
      form.endDate = "";
    }
  }
);

const onSearch = async () => {
  try {
    loading.value = true;
    await syncTaskStatus();
    const { time, ...reset } = form;
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...reset
    };
    const { data } = await getUserTasks(params);
    const { records, total, size, current } = data;
    tableData.value = records.map((item: any) => {
      const progress = item?.progress.split("%")[0] || 0;
      return {
        ...item,
        progress: +progress,
        inputLoading: false,
        outputLoading: false
      };
    });
    pagination.total = total;
    pagination.pageSize = size;
    pagination.currentPage = current;
  } finally {
    loading.value = false;
  }
};
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
  form.startDate = "";
  form.endDate = "";
  pagination.currentPage = 1;
  onSearch();
};
onMounted(() => {
  onSearch();
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>
